/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *reverseBetween(ListNode *head, int m, int n) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
		if (m == n) {
			return head;
		}

		ListNode* pre = NULL;
		ListNode* first = NULL;

		if (m == 1) {
			first = head;
		} else {
			pre = head;
			for (int i = 0; i < m - 2; ++i) {
				pre = pre->next;
			}
			first = pre->next;
		}

		ListNode* cur = first;
		ListNode* next = cur->next;

		for (int i = 0; i < n - m; ++i) {
			ListNode* tmp = next->next;
			next->next = cur;
			cur = next;
			next = tmp;
		}

		if (pre != NULL) {
			pre->next = cur;
			first->next = next;
		} else {
			head = cur;
			first->next = next;
		}
		return head;
    }
};